package Thread_lock;

import java.util.concurrent.atomic.AtomicReference;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/5/29
 * Time:18:38
 * 产生ABA问题
 **/
public class Demo4 {

    private static AtomicReference money = new AtomicReference(100);//初始值

    public static void main(String[] args) throws InterruptedException {

        //定义两个转账的线程
        //-100
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                boolean result = money.compareAndSet(100,0);//compareAndSet(A,B),转走了100
                System.out.println("第一次转账："+result);
            }
        });
        t1.start();
        t1.join();

        //+100
        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                boolean result = money.compareAndSet(0,100);//compareAndSet(A,B),转进了100
                System.out.println("转入："+result);
            }
        });
        t3.start();
        t3.join();

        //-100
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                boolean result = money.compareAndSet(100,0);//compareAndSet(A,B),转走了100
                System.out.println("第二次转账："+result);
            }
        });
        t2.start();


    }
}
